<?php
/**
 * Created by PhpStorm.
 * User: lhl
 * Date: 2020/10/21
 * Time: 13:09
 * Features:IP白名单检测
 */

namespace app\adminapiv3\middleware;

use app\common\service\ApiHelper;
use app\common\service\platform_manage\ServerAllowIpService;
use think\Request;

class CheckIp
{
    //IP白名单检测忽略控制器
    const ignoreController = [
        'install',
        'test',
        'index',
        'login'
    ];

    //IP白名单检测忽略具体方法 TODO 注意控制器转换为小写后 多级控制器的写法需要去掉下划线 因为$request->controller() 方法返回的是控制器的大驼峰格式！！
    const ignoreRoute = [
        'platformmanage.serverauth/platformauthinfo',
        'modulemanage.netfilter.rulepreview/pushtoserver',//本地规则排序组件 推送 排序后规则
    ];

    //响应码
    private $responseCode = [];

    public function handle(Request $request, \Closure $next)
    {
        //状态码
        $this->responseCode = ApiHelper::getCode();

        //真实路由 = 控制器/方法 $request->controller() 方法返回的是控制器的大驼峰格式！！
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $route = $controller.'/'.$action;
        //忽略检测的控制器
        if(in_array($controller, self::ignoreController)){
            return $next($request);
        }

        //忽略检测的具体方法
        if(in_array($route,self::ignoreRoute)){
            return $next($request);
        }

        $userIp = $request->ip();
        $allowIpServer = new ServerAllowIpService();
        $allowIpInfo = $allowIpServer->findData(['ip' => $userIp]);
        if(!$allowIpInfo){
            returnErrJson($this->responseCode['not_ip_error'], '非法IP');
        }

        return $next($request);
    }

}